package org.khd.auth.controller;

import org.khd.auth.context.LoginContext;
import org.khd.auth.dto.LoginDto;
import org.khd.base.utils.AjaxResult;
import org.khd.org.domain.Employee;
import org.khd.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class authLoginController {

    @Autowired
    private IEmployeeService employeeService;

    @PostMapping
    public AjaxResult login(@RequestBody LoginDto loginDto){
        Employee employee = employeeService.getByUsername(loginDto.getUsername());
        if (employee != null){
            if (employee.getPassword().equals(loginDto.getPassword())){
                //登录成功
                //生成TOKEN(唯一不重复)
                String token = UUID.randomUUID().toString();
                //Employee脱敏处理
                employee.setPassword("");
                //往全局map里面存放数据
                LoginContext.context.put(token,employee);
                //组装返回到前端的数据(token,当前的登录用户)
                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                map.put("user", employee);
                return AjaxResult.ARDefault().setMsg("登录成功").setData(map);
            }else {
                //密码错误，登录失败
                return AjaxResult.ARDefault()
                        .setSuccess(false)
                        .setMsg("账号与密码不匹配，登录失败");
            }

        }else {
            //根据用户名没有找到用户
            //密码错误，登录失败
            return AjaxResult.ARDefault()
                    .setSuccess(false)
                    .setMsg("账号与密码不匹配，登录失败");

        }

    }
}
